import axios from 'axios'
import store from '../store'
import {
  USER_KEY
} from '../utils/constant'
import {
  removeUser
} from '../store/userReducer'


const instance = axios.create({
  baseURL: process.env.REACT_APP_URL
})
instance.interceptors.request.use(async config => {
  const state = await store.getState()

  const user = state[USER_KEY].user
  if (user && user.token) {
    if (!config.headers) {
      config.headers = {}
    }
    config.headers.Authorization = `Bearer ${user.token}`
  }
  return config
}, err => {
  return Promise.reject(err)
})
instance.interceptors.response.use(res => {
  if (res.data.status === 410000) {
    store.dispatch(removeUser())
  }
  return res
}, err => {
  return Promise.reject(err)
})

const request = config => instance(config).then(res => res.data)

request.get = (url, params) => instance.get(url, {
  params
}).then(res => res.data)

request.post = (url, body) => instance.post(url, body).then(res => res.data)


export const signIn = (body) => {
  return request.post('/login', body)
}
export const signout = () => {
  return request.get('/setting/admin/logout')
}
export const getProduct = (params) => {
  return request.get('/product/product', params)
}
export const getCaptcha = () => {
  return request({
    method: 'get',
    url: '/captcha_pro',
    responseType: 'blob'
  })
}

export default request